<?php

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelPublish extends JModel
{	
	public function publish()
	{
		$cid = JRequest::getVar('cid', array(0), 'post', 'array');
				
		foreach($cid as $id) {
			$item = $this->_getItem($id);
			
			if ($item) {
				if (!$this->storeContent($item)) {
					$title = json_decode($item->data);
					$title = $title->title;
					return JText::sprintf('COULD_NOT_POST_CONTENT_TITLED_%s', $title);
				}
				
				// remove from hold
				if (!$this->removeHold($item)) {
					$title = json_decode($item->data);
					$title = $title->title;
					return JText::sprintf('COULD_NOT_REMOVE_CONTENT_TITLED_%s', $title);
				}
			}
		}
		
		return true;
	}
	
	private function _getItem($id)
	{
		$db =& JFactory::getDBO();
		
		$query = 'SELECT id'
			   .', data'
			   .', category'
			   .' FROM #__syncr_hold'
			   .' WHERE id = '.$id;
			   ;
		$db->setQuery($query);
		
		return $db->loadObject();
	}
	
	public function storeContent($item)
	{
		$row =& $this->getTable('com_content', 'Table');
					
		$json = json_decode($item->data);
		$post['title'] = $json->title;
		$post['alias'] = $json->alias;
		$post['introtext'] = $json->introtext;
		$post['fulltext'] = $json->fulltext;
		$post['state'] = $json->state;
		$post['created'] = $json->created;
		$post['created_by'] = $json->created_by;
		$post['created_by_alias'] = $json->created_by_alias;
		$post['modified'] = $json->modified;
		$post['modified_by'] = $json->modified_by;
		$post['publish_up'] = $json->publish_up;
		$post['publish_down'] = $json->publish_down;
		$post['attribs'] = $json->attribs;
		$post['version'] = $json->version;
		$post['metakey'] = $json->metakey;
		$post['metadesc'] = $json->metadesc;
		$post['access'] = $json->access;
		$post['metadata'] = $json->metadata;
		
		
		$post['sectionid'] = $this->_getSection($item->category);
		$post['catid'] = $item->category;
		
		$post['id'] = null;
		
		if (!$row->bind($post)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
	
	public function removeHold($item) {
		$row =& $this->getTable('hold', 'Table');
				
		$id = (int) $item->id;
		if (!$row->delete($id)) {
			return false;
		}
		
		return true;
	}
	
	private function _getSection($catid)
	{
		$db = &JFactory::getDBO();
		
		$query = 'SELECT section'
			   .' FROM #__categories'
			   .' WHERE id = '.$catid
			   ;
		
		$db->setQuery($query);
		return $db->loadResult();
	}
}